<template>
  <div>
    <panel title="添加账号">
      <el-form
        :model="ruleForm"
        :rules="rules"
        status-icon
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="账号" prop="account">
          <el-input class="account" v-model="ruleForm.account"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            class="password"
            v-model="ruleForm.password"
            type="password"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="用户组" prop="userGroup">
          <el-select v-model="ruleForm.userGroup" placeholder="请选择用户组">
            <el-option label="普遍管理员" value="普遍管理员"></el-option>
            <el-option label="超级管理员" value="超级管理员"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button @click="submit" type="primary">提交</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </panel>
  </div>
</template>

<script>
import Panel from "../../components/panel/Panel.vue";
import { addAccount } from "../../api/user";


import { isAccount } from "../../utils/tools.js";


export default {
  components: {
    Panel,
  },
  data() {
    // 验证账号
    const checkAccount = (rule, value, callback) => {
      if (!value) {
        callback(new Error("账号不能为空"));
      } else if (!isAccount(value)) {
        callback(new Error("3 ~ 12 位,数字/字母/"));
      } else {
        callback();
      }
    };
    // 验证密码
    const checkPass = (rule, value, callback) => {
      if (!value) {
        callback(new Error("密码不能为空"));
      } else if (!isAccount(value)) {
        callback(new Error("3 ~ 12 位,字母/数字/"));
      } else {
        callback();
      }
    };

    return {
      ruleForm: {
        account: "",
        password: "",
        userGroup: "",
      },
      // 验证规则
      rules: {
        // account: [{ required: true, message: "账号不能为空", trigger: "blur" }],  内置验证

        account: { required: true, validator: checkAccount, trigger: "blur" },
        password: { required: true, validator: checkPass, trigger: "blur" },
        userGroup: {
          required: true,
          message: "请选择用户组",
          trigger: "change",
        },
      },
    };
  },
  methods: {
    submit() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          try {
            let res=await addAccount(this.ruleForm)
            if(res.data.code===0){
              this.$router.push('/account/account-list')
             local.clear();
            }
          } catch (err) {console.log(err);}

        } else {
          return;
        }
      });
    },
    // 重置
    reset() {
      this.$refs.ruleForm.resetFields();
    },
  },
};
</script>

<style lang="less" scoped>
.password,
.account {
  width: 300px;
}
</style>
